﻿using Prism.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Common;
using ZoneLineNew.Enums;
using ZoneLineNew.Models.StationConfig;
using ZoneLineNew.Models.StationResult.HOPStation;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Print;

namespace ZoneLineNew.Services.Station.HOPStation {
    /// <summary>
    /// 衬套压装工位
    /// </summary>
    /// <remarks>
    /// <para>StationCode：OP620</para>
    /// <para>IP：192.168.10.10</para>
    /// </remarks>
    public class HOP010StationService : WorkStationBaseService<HOP010StationResult, HOP010StationConfig> {
        
        public HOP010StationService(
            IDbOperate<IFreeSqlMainContext> mainDbOperate, 
            IEventAggregator eventAggregator,
            PrinterLabelService printerService
            )
            : base(mainDbOperate, eventAggregator, printerService) {


            base.InitReSetAddr();
        }

        public override void DealData(byte[] content) {
            StationRecordData.AbsScanCode = GetPlcString(content, 280);
            //StationRecordData.BushScanCode = GetPlcString(content, 322);
            StationRecordData.PartType = GetPlcString(content, 1002);
            StationRecordData.Result = _client.ByteTransform.TransInt16(content, 1000).ToString().Equals("1") ? _okCode : _ngCode;
            StationRecordData.PressPosition = _client.ByteTransform.TransSingle(content, 1016);
            StationRecordData.PressForce = _client.ByteTransform.TransSingle(content, 1020);
            StationRecordData.CycleTime = _client.ByteTransform.TransSingle(content, 1024);
            
            //批次追溯
            StationRecordData.BushScanCode = _client.ReadString("DB1100.DBX0").Content;
        }

        public override void DealWithCommonData(byte[] content) {
            Heart = _client.ByteTransform.TransInt16(content, 8) == (short)1;
            StartUploadCode = _client.ByteTransform.TransInt16(content, 6) == (Int16)1;
            StartUploadData = _client.ByteTransform.TransInt16(content, 10) == (Int16)1;

            HeartToPlc = _client.ReadInt16("DB1001.DBW0").Content == (Int16)1;
            EndUpLoadCode = _client.ReadInt16("DB1001.8").Content == (Int16)1;
            EndUpLoadData = _client.ReadInt16("DB1001.2").Content == (Int16)1;
            AllowWork = _client.ReadInt16("DB1001.8").Content;
        }

        public override async void DealWithSignal(string signalName)
        {

            if (signalName == nameof(StartUploadCode))
            {
                //todo 上传了条码 这时候验证是否要工作
                if (StartUploadCode)
                {
                    LogWithUi($"在{CurrentStationName}收到上传条码信息命令", StationRecordData.AbsScanCode);

                    #region 验证缸体码是否合格
                    LogWithUi($"在{CurrentStationName}工位检查缸体码是否合格", StationRecordData.AbsScanCode);
                    var codeRes = base.MainCodeVerify(StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}工位检查缸体码是否合格{StationRecordData.AbsScanCode}的结论是{codeRes}", StationRecordData.AbsScanCode);
                    if (!codeRes) {
                        LogWithUi($"在{CurrentStationName}工位检查缸体码不合格", StationRecordData.AbsScanCode);
                        var writeRlt0 = WriteWorkActionToPlc(StationConfig.AllowWorkAddr, WorkActionEnum.CodeErr, StationRecordData.AbsScanCode);
                        LogWithUi($"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt0}", StationRecordData.AbsScanCode);
                        return;
                    }
                    #endregion

                    #region 检查来料是否合格
                    LogWithUi($"在{CurrentStationName}检查来料是否合格", StationRecordData.AbsScanCode);
                    var mesRes = await ApiHelper.CheckIncomingMaterialIsOKAsync(StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}{mesRes.errorMsg}", StationRecordData.AbsScanCode);
                    if (!mesRes.IsOk)
                    {
                        LogWithUi($"在{CurrentStationName}{mesRes.errorMsg}", StationRecordData.AbsScanCode);
                        var writeRlt0 = WriteWorkActionToPlc(StationConfig.AllowWorkAddr, WorkActionEnum.CalHErr, StationRecordData.AbsScanCode);
                        LogWithUi($"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt0}", StationRecordData.AbsScanCode);
                        return;
                    }
                    #endregion

                    LogWithUi($"在{CurrentStationName}工位结论验证,条码信息是{StationRecordData.AbsScanCode}", StationRecordData.AbsScanCode);
                    var validataRlt = Validata(CurrentStationName, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}工位的验证结果是{validataRlt}", StationRecordData.AbsScanCode);
                    var writeRlt = WriteWorkActionToPlc(StationConfig.AllowWorkAddr, validataRlt, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}工位向下位机下发消息，下发{writeRlt}", StationRecordData.AbsScanCode);
                }
                else
                {
                    LogWithUi($"在{CurrentStationName}收到上传条码命令变为false", StationRecordData.AbsScanCode);
                    WriteData(StationConfig.EndUploadCodeAddr, 0, StationRecordData.AbsScanCode);
                    WriteData(StationConfig.AllowWorkAddr, 0, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}复位工作控制指令和复位上传条码完成指令", StationRecordData.AbsScanCode);
                }
                return;
            }

            if (signalName == nameof(StartUploadData))
            {
                //todo 上传数据 这时候将数据记录到数据库中
                if (StartUploadData)
                {
                    LogWithUi($"在{CurrentStationName}收到上传记录数据命令", StationRecordData.AbsScanCode);
                    var rlt = RecordData();
                    WriteData(StationConfig.EndUploadDataAddr, (short)rlt, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}数据记录,rlt={rlt}", StationRecordData.AbsScanCode);
                }
                else
                {
                    LogWithUi($"在{CurrentStationName}收到上传记录数据命令变为false", StationRecordData.AbsScanCode);
                    WriteData(StationConfig.EndUploadDataAddr, (short)0, StationRecordData.AbsScanCode);
                    LogWithUi($"在{CurrentStationName}数据记录,clear", StationRecordData.AbsScanCode);
                }
            }
        }

        public override int RecordData() {
            var result = new HOP010StationResult() {
                AbsScanCode = StationRecordData.AbsScanCode,
                StationCode = StationConfig.StationCode,
                PartType = StationRecordData.PartType,
                Result = StationRecordData.Result,
                PressPosition = StationRecordData.PressPosition,
                PressForce = StationRecordData.PressForce,
                CycleTime = StationRecordData.CycleTime,
                CreateTime = DateTime.Now,
                ProductID = Cache.CurWorkProduct.Id,
                //以下是批次追溯
                BushScanCode = StationRecordData.BushScanCode,
            };
            var writeRlt = false;
            if (_mainDbOperate.CheckExist<HOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode && !result.IsReworked)) {
                var beforeRlt = _mainDbOperate.GetModel<HOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode && !result.IsReworked);
                result.Id = beforeRlt.Id;
                writeRlt = _mainDbOperate.UpdateModelSuper<HOP010StationResult>(p => p.AbsScanCode == result.AbsScanCode && !result.IsReworked, result);
                LogWithUi($"在{CurrentStationName}工位数据更新,rlt={writeRlt}", StationRecordData.AbsScanCode);
            } else {
                writeRlt = _mainDbOperate.AddModel(result);
                LogWithUi($"在{CurrentStationName}工位数据新增,rlt={writeRlt}", StationRecordData.AbsScanCode);
            }
            return writeRlt ? 1 : 2;
        }
    }




}
